/* eslint-disable global-require */
/* eslint-disable import/no-extraneous-dependencies */
const path = require("path");
const webpack = require("webpack");

// 自动产出html
const HtmlWebpackPlugin = require("html-webpack-plugin");
// 分类css
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// 内联css
// eslint-disable-next-line no-unused-vars
const HtmlInlineCssWebpackPlugin = require("html-inline-css-webpack-plugin").default;
// 压缩js
const TerserWebpackPlugin = require("terser-webpack-plugin");
// 压缩css
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");
// 将第三方模块添加到html中 并且自动将配置中的模块添加到externals属性中让webpack忽略打包
const HtmlWebpackExternalsPulgin = require("html-webpack-externals-plugin");

// 清理输入目录
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

// eslint-disable-next-line no-unused-vars
const HtmlWebpackExternalsPlugin = require("html-webpack-externals-plugin");
// 拷贝静态文件
// eslint-disable-next-line no-unused-vars
const CopyWebpackPlugin = require("copy-webpack-plugin");

//日志美化插件
//const FriendlyErrorsWebpackPlugin = require("friendly-errors-webpack-plugin");

//费事分析
const SpeedMeasureWebpackPlugin = require("speed-measure-webpack-plugin");
const smw = new SpeedMeasureWebpackPlugin();

//生成代码分析报告
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");

// 环境变量
// eslint-disable-next-line no-console
// console.log(process.env.NODE_ENV);
// process.env.NODE_ENV = "production";

// 打包后静态文件存放目录
const staticFolder = "./dist";


// module.exports = (env) => {
//     // eslint-disable-next-line no-unused-vars
//     //const isProduction = env === "production";
//     return {}
// }

module.exports = smw.wrap({
    mode: "development", // development、production、null
    entry: {
        index: "./src/index.js",
        common: "./src/common.js",
    },
    output: {
        path: path.resolve(__dirname, staticFolder),
        filename: "[name].[chunkhash].js",
        publicPath: "/",
    },
    devtool: "source-map", // /eval-source-map
    devServer: {
        contentBase: path.resolve(__dirname, staticFolder),
        host: "localhost",
        port: "8888",
        compress: true,
        progress: true,
        // proxy: {
        //     "/api": 'http://localhost:3000'
        // },

        // 代理请求服务器
        proxy: {
            "/api": {
                target: "http://localhost:3000",
                pathRewrite: { "^/api": "" },
            },
        },
    },
    resolve: {
        // 指定extension之后可以不用在require或是import的时候加文件扩展名,会依次尝试添加扩展名进行匹配
        extensions: [".js", ".jsx", ".json", ".css"],
        // 配置别名可以加快webpack查找模块的速度
        alias: {
            bootstrapcss: path.resolve(__dirname, "node_modules/bootstrap/dist/css/bootstrap.css"),
        },
        // 设置多个模块查找路径 从左到右
        // modules: ["mynode_modules","node_modules"],
        // 配置 target === "web" 或者 target === "webworker" 时 mainFields 默认值是：
        // mainFields: ['browser', 'module', 'main'],
        // target 的值为其他时，mainFields 默认值为：
        // mainFields: ["module", "main"],
        // 当目录下没有 package.json 文件时，我们说会默认使用目录下的 index.js 这个文件，其实这个也是可以配置的
        // mainFiles: ['index'], // 你可以添加其他默认使用的文件名
    },
    // 默认false,也就是不开启
    // watch: true,
    // // 只有开启监听模式时，watchOptions才有意义
    // watchOptions: {
    //     ignored: /node_modules/, // 默认为空，不监听的文件或者文件夹，支持正则匹配
    //     aggregateTimeout: 300, // 监听到变化发生后会等300ms再去执行，默认300ms
    //     poll: 1000, // 判断文件是否发生变化是通过不停的询问文件系统指定议是有变化实现的，默认每秒问1000次
    // },
    // 如果我们想引用一个库，但是又不想让webpack打包，并且又不影响我们在程序中以CMD、AMD或者window/global全局等方式进行使用，那就可以通过配置externals
    // externals禁止webpack打包库到项目中
    // HtmlWebpackExternalsPulgin 通过cdn方式导入库到页面
    // externals:{
    //     React:"react",              //React全局变量: "react" 库的名称
    //     ReactDom:"react-dom",
    //     moment:"moment"
    // },
    module: {
        rules: [

            {
                test: /\.(js|jsx|ts)$/,
                include: path.resolve(__dirname, "src"),
                exclude: /node_modules/,
                use: [{
                    loader: "eslint-loader",
                    options: {
                        fix: true,
                    },
                }, {
                    loader: "babel-loader",
                    options: {
                        // @babel/preset-env 解析javasctipt高级语法的一个预设
                        presets: ["@babel/preset-env"],
                        plugins: [
                            ["@babel/plugin-proposal-decorators", { legacy: true }], // 解析javascript装饰器 切必须放置在@babel/plugin-proposal-class-properties前面
                            ["@babel/plugin-proposal-class-properties", { loose: true }],
                            ["@babel/plugin-transform-runtime", { // 将 babel添加在文件中公共的辅助代码抽离单独的文件中，减少打包后文件的的体积
                                corejs: false,
                                helpers: true,
                                regenerator: true,
                                useESModules: true,
                            }],
                        ],
                    },
                }],
            },
            {
                test: /\.css$/,
                include: path.resolve(__dirname, "src"),
                exclude: /node_modules/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                }, "css-loader", {
                    loader: "postcss-loader",
                    // options:{
                    //     plugins:[require('autoprefixer')]
                    // }
                }],
            },
            {
                test: /\.less$/,
                include: path.resolve(__dirname, "src"),
                exclude: /node_modules/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                }, "css-loader", "less-loader"],
            }, {
                test: /\.scss$/,
                include: path.resolve(__dirname, "src"),
                exclude: /node_modules/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                }, "css-loader", "sass-loader"],
            }, {
                test: /\.(jpg|jpeg|png|bmp|gif|svg)$/,
                use: [{
                    loader: "url-loader",
                    options: {
                        limit: 1024,
                        // 将图片存放在单独的文件夹中
                        outputPath: "images", // 指定输出的路径
                        publicPath: "/images", // 指定构建后写入html中的路径
                    },
                },
                // ,{
                //     loader: "image-webpack-loader",
                //     options: {
                //         mozjpeg: {          //Compress JPEG images
                //             progressive: true,
                //             quailty: 65,
                //         },
                //         // optipng.enabled: false will disable optipng
                //         optipng: {          //Compress PNG images
                //             enabled: false,
                //         },
                //         pngquant: {         //Compress PNG images
                //             quality: [0.65, 0.90],
                //             speed: 4
                //         },
                //         gifsicle: {         //Compress GIF images
                //             interlaced: false,
                //         },
                //         // the webp option will enable WEBP
                //         webp: {
                //             quality: 75
                //         }
                //     }
                // }
                ],
            }, {
                test: /\.(woff|ttf|eot|svg|otf)$/,
                use: [{
                    loader: "url-loader",
                    options: {
                        limit: 1024,
                        outputPath: "fonts", // 指定输出的路径
                        publicPath: "/fonts", // 指定构建后写入html中的路径
                    },
                }],
            },
        ],
    },
    optimization: {
        minimizer: [
            // 压缩css支持es6语法
            new TerserWebpackPlugin({
                parallel: true,
                cache: true,
            }),
            // 压缩css
            new OptimizeCssAssetsWebpackPlugin({
                assetNameRegExp: /\.css$/g,
                // eslint-disable-next-line global-require
                cssProcessor: require("cssnano"),
            }),
        ],
    },
    stats:'normal',
    plugins: [
        // webpack配置ProvidePlugin后，在使用时将不再需要import和require进行引入，直接使用即可
        new webpack.ProvidePlugin({
            _: "lodash",
        }),
        // IgnorePlugin用于忽略某些特定的模块，让 webpack 不把这些指定的模块打包进去
        new webpack.IgnorePlugin(/^\.\/locale/, /moment$/),
        // 抽离css到单独的文件中
        new MiniCssExtractPlugin({
            // filename: '[name].[contenthash].css',
            // chunkFilename: '[name].[contenthash].css',
            // 将打包后的css单独存放在styles文件夹中
            filename: "styles/[name].[contenthash].css",
            chunkFilename: "styles/[name].[contenthash].css",
        }),
        new HtmlWebpackExternalsPulgin({
            externals: [
                {
                    module: "react",
                    entry: "https://cdn.bootcss.com/react/15.6.1/react.js",
                    global: "React",
                },
                {
                    module: "react-dom",
                    entry: "https://cdn.bootcss.com/react/15.6.1/react-dom.js",
                    global: "ReactDOM",
                }, {
                    module: "moment",
                    entry: "https://cdn.bootcdn.net/ajax/libs/moment.js/2.26.0/moment.min.js",
                    global: "moment",
                },
            ],
        }),
        // 通过模板文件自动产出html
        new HtmlWebpackPlugin({
            title: "webapck build html",
            template: "./public/index.html",
            filename: "index.html",
            inject: true,
            hash: true,
            chunks: ["common", "index"],
            chunksSortMode: "manual",
            excludeChunks: ["demo"],
            favicon: "./favicon.ico",
            meta: {
                viewport: "width=device-width, initial-scale=1, shrink-to-fit=no",
            },
            base: {
                href: "http://localhost:8888",
                target: "_blank",
            },
            minify: false,
            cache: true,
        }),
        // 清理输入目录
        new CleanWebpackPlugin({
            cleanOnceBeforeBuilderPatterns: ["**/*", "!static-files*"],
        }),
        // 添加注释到每个模块最顶部
        new webpack.BannerPlugin("Leo Copyright"),
        // 拷贝静态文件
        // new CopyWebpackPlugin({
        //     patterns: [
        //         {
        //             from: path.resolve(__dirname, "src/data"),
        //             to: path.resolve(__dirname, "dist/data"),
        //         },
        //     ],
        // }),
        // 抽离的css转为静态的内联css style-loader将css转为为js模块在程序运行时动态导入css
        // new HtmlInlineCssWebpackPlugin(),
        //日志美化插件
        ///new FriendlyErrorsWebpackPlugin(),

        //生成代码分析报告
        new BundleAnalyzerPlugin({
            analyzerMode: 'disabled', // 不启动展示打包报告的http服务器
            generateStatsFile: true, // 是否生成stats.json文件
        }),
    ],

});